package org.jlamp.core.util;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * 文件读写工具类
 *
 * @author zhangcs
 * @since 1.0
 */
public class FileUtils {

    /**
     * 读取文件内容
     *
     * @param file 指定文件
     * @return 返回内容字符串
     * @throws IOException
     */
    public static String read(File file) throws IOException {
        try (Reader reader = new InputStreamReader(new FileInputStream(file.getAbsolutePath()), "UTF-8");) {
            StringBuilder sb = new StringBuilder();
            char[] buf = new char[1];
            while ((reader.read(buf)) != -1) {
                sb.append(buf);
            }

            return sb.toString();
        }
    }

    /**
     * 写文件
     *
     * @param content 需要写的内容
     * @param file    文件
     * @throws IOException
     */
    public static void write(String content, File file) throws IOException {
        try (Writer writer = new OutputStreamWriter(new FileOutputStream(file.getAbsolutePath()), "UTF-8")) {
            writer.write(content);
            writer.flush();
        }
    }

}
